package com.lijinquan.springcloud.controller;

import cn.lijinquan.p2p.entites.Product;
import cn.lijinquan.p2p.entites.ProductEarningRate;
import cn.lijinquan.p2p.entites.ResultMap;
import com.lijinquan.springcloud.constants.FrontStatusConstants;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lijinquan on 2019/10/4.
 */
@RestController
public class ProductRateController {
    private static final String REST_URL_PREFIX = "http://P2P-WEB/";
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 查询产品年利率
     * @param request
     * @return
     */
    @RequestMapping("/productRate/yearInterest")
    public ResultMap<List<Map<String,Object>>> getyearInterest(HttpServletRequest request) {
        ResultMap<List<Map<String,Object>>> rm = new ResultMap<>();
        String pid = request.getParameter("pid");
        String token = request.getHeader("token");
        Map<Object, Object> tokenmap = restTemplate.getForObject(REST_URL_PREFIX + "user/getTokenFromRedis/" + token, Map.class);
        if (tokenmap == null || tokenmap.size() == 0) {
            rm.setStatus(FrontStatusConstants.NOT_LOGGED_IN);// 用户未登录
            return rm;
        }
        //1.根据pid获取理财产品利率
        if(StringUtils.isEmpty(pid)){
            rm.setStatus(FrontStatusConstants.HAS_NOT_CHOOSED_PRODUCT);//pid为空则说明没选择理财产品
            return rm;
        }
        Product product = restTemplate.getForObject(REST_URL_PREFIX + "product/findProductById/" + Integer.valueOf(pid), Product.class);
        List<ProductEarningRate> proEarningRate = product.getProEarningRate();
        List<Map<String,Object>> list= new ArrayList<>();
        if(proEarningRate.size()>0){
            for (ProductEarningRate pr:proEarningRate){
                Map<String,Object> map= new HashMap<>();
                map.put("incomeRate",pr.getIncomeRate());
                map.put("endMonth",pr.getMonth());
                list.add(map);
            }
        }
        rm.setBody(list);
        //
        return rm;
    }


}
